package com.helloandroid.models

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.helloandroid.AppUtil
import com.helloandroid.MyApplication
import com.helloandroid.app.model.AppCache
import com.helloandroid.ext.parseCoinAndMoney
import com.helloandroid.ext.parseTxRecord
import com.helloandroid.ext.process
import com.helloandroid.tools.GUtils.httpWithTimeOut
import com.helloandroid.tools.Http.asyncHttpReq
import com.helloandroid.tools.MyLog
import com.helloandroid.tools.NetWorkUtil
import com.helloandroid.vo.CoinAndMoney
import com.helloandroid.vo.TxInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.json.JSONObject

class TxViewModel : ViewModel() {

    fun getInfo(callback: (Boolean,TxInfo?) -> Unit){

        val info = AppCache.copyTxInfo()
        if (info != null){
            callback(true,info)
            return
        }

        if (!NetWorkUtil.networkConnected()){
            AppUtil.toast("请打卡网络!")
            callback(false,null)
            return
        }

        viewModelScope.launch {
             val defer = async(Dispatchers.IO){
                asyncHttpReq("tx/info?user_id=${AppUtil.user.user_id}")
            }
            val jsonStr = defer.await()
            val jsonObj = JSONObject(jsonStr)
            val parseResult = jsonObj.parseTxRecord()
            if (parseResult.err == 0){
                val txInfo = parseResult.obj as TxInfo
                AppCache.txInfo = txInfo
                callback(true,AppCache.copyTxInfo())
            }else{
                MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
                callback(false,null)
            }
        }
    }


    // 将玩家所有的金币兑换成  money
    fun chgMoney(callback:(Boolean)->Unit){
        if (!NetWorkUtil.networkConnected()){
            AppUtil.toast("请打开网络!")
            callback(false)
            return
        }
        viewModelScope.launch {
            httpWithTimeOut(10000L, suspend {
                asyncHttpReq("tx/duihuan?user_id=${AppUtil.user.user_id}&coin=${AppUtil.user.coin}")
            }){jsonStr->
                if (jsonStr.isNullOrEmpty()){
                    callback(false)
                }else{
                    val jsonObj = JSONObject(jsonStr)
                    val parseResult = jsonObj.process(JSONObject::parseCoinAndMoney)
                    if(parseResult.err == 0){
                        val coinAndMoney = parseResult.obj as CoinAndMoney
                        val user = AppUtil.user
                        user.coin = coinAndMoney.coin
                        user.money = coinAndMoney.money
                        callback(true)
                    }else{
                        MyLog.info("err:${parseResult.err},msg:${parseResult.msg}")
                        callback(false)
                    }
                }
            }

//            withTimeout(10000L){
//                try {
//                    val jsonStr = asyncHttpReq("tx/duihuan?user_id=${AppUtil.user.user_id}&coin=${AppUtil.user.coin}")
//                    val jsonObj = JSONObject(jsonStr)
//                    val parseResult = jsonObj.process(JSONObject::parseCoinAndMoney)
//                    if(parseResult.err == 0){
//                        val coinAndMoney = parseResult.obj as CoinAndMoney
//                        val user = AppUtil.user
//                        user.coin = coinAndMoney.coin
//                        user.money = coinAndMoney.money
//                        callback(true)
//                    }else{
//                        MyLog.elog("err:${parseResult.err},msg:${parseResult.msg}")
//                        callback(false)
//                    }
//                }catch (e:Exception){
//                    // 超时
//                    callback(false)
//                }
//            }
        }
    }

//    private suspend fun httpChgMoney():String{
//        NetWorkUtil.mockDelay()
//        val user = MyApplication.user
//        val coinAndMoney = CoinAndMoney(
//                coinCount = 0,
//                moneyCount = user.coin + user.money
//        )
//        return jsonObject(
//                "err" to 0,
//                "data" to GUtils.getGson().toJson(coinAndMoney)
//        ).toString()
//    }
}